<template>
  <view>
    <nav-bar :page-title="lang.page_name"/>

    <view :class="['padding-30',locale]" style="padding-bottom: 460rpx">
      <view class="flex-column" style="font-size:28rpx;gap: 18rpx">

        <!-- 预览-->
        <file-name-card @onView="openPreview" :title="files.name" :total-page="pageSize"/>

        <!-- 选择打印纸-->
        <my_form_item :label="lang.paper_type">
          <template #left_content>
            <radio-group @change="onPaperType" v-model="paperSize" class="flex-center text-32 gap-30">
              <label for="A3" class="flex-center gap-8"> {{ lang.a3 }}
                <radio id="A3" :disabled="!getCanPaper(printer.paper_types_supported, 'A3')" color="#07c160" value="8"
                       class="transform-nine"/>
              </label>
              <label for="A4" class="flex-center gap-8"> {{ lang.a4 }}
                <radio id="A4" checked color="#07c160" value="9" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <!-- 选择打印数量-->
        <my_form_item :label="lang.printNums">
          <template #left_content>
            <u-number-box v-model="nums" @change="onNums" :min="1" :max="50" integer/>
          </template>
        </my_form_item>

        <!-- 页面数量-->
        <my_form_item :label="lang.printRange">
          <template #left_content>
            <input-range :page-size="pageSize" @blur="handleRangeChange"/>
          </template>
        </my_form_item>

        <!-- 双面打印-->
        <my_form_item v-if="printer.supports_double_side === 1 && pageSize >=1" :label="lang.double_print">
          <template #left_content>
            <view class="flex-center gap-8">
              <switch @change="onDouble" color="#07c160"/>
            </view>
          </template>
        </my_form_item>

        <!-- 双面分类-->
        <my_form_item v-if="isDoubleSided" :label="lang.double_type">
          <template #left_content>
            <radio-group @change="onRadioEdgeChange" v-model="radioEdge" class="flex-center text-32 gap-30">
              <!-- 短边 -->
              <label for="3" class="flex-center gap-8"> {{ lang.short_edge }}
                <radio id="3" :checked="radioEdge==='3'" color="#07c160" value="3" class="transform-nine"/>

              </label>
              <!-- 长边-->
              <label for="2" class="flex-center gap-8"> {{ lang.long_edge }}
                <radio id="2" :checked="radioEdge==='2'" color="#07c160" value="2" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <!-- 彩色打印-->
        <my_form_item v-if="printer.supports_color === 1" :label="lang.print_color">
          <template #left_content>
            <view class="flex-center gap-8">
              <switch @change="onPrintColor" :checked="printColor" color="#07c160"/>
            </view>
          </template>
        </my_form_item>

        <!-- 打印方向-->
        <my_form_item :label="lang.orientation">
          <template #left_content>
            <radio-group @change="onOrientationRadioGroup" v-model="radioCurrent" class="flex-center text-32 gap-30">
              <!-- 横向 -->
              <label for="horizontal" class="flex-center gap-8"> {{ lang.horizontal }}
                <radio id="horizontal" color="#07c160" value="2" class="transform-nine"/>
              </label>
              <!-- 竖向-->
              <label for="vertical" class="flex-center gap-8"> {{ lang.vertical }}
                <radio id="vertical" checked color="#07c160" value="1" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <!-- 内容自动旋转-->
        <my_form_item :label="lang.automaticRotation">
          <template #left_content>
            <radio-group @change="onAutomaticRotation" v-model="automaticRotation" class="flex-center text-32 gap-30">
              <!-- 关闭 -->
              <label for="close" class="flex-center gap-8"> {{ otherLang.close }}
                <radio id="close" color="#07c160" value="0" class="transform-nine"/>
              </label>
              <!-- 开启-->
              <label for="open" class="flex-center gap-8"> {{ otherLang.open }}
                <radio id="open" checked color="#07c160" value="1" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <pay-card :pay-price="totalPrice" @on-pay="printPay" :is-file="true" @on-preview="onFilePreview"/>
      </view>
    </view>
    <!-- 上传中-->
    <my_upload_card :upload-progress="uploadProgress" :upload-name="files.name" :show="showUpload"/>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/nav-bar.vue";
import my_form_item from "@/components/my_form_item/index.vue";
import {getCanPaper, getFileExtension} from "@/utils/utils";
import heraaCell from "@/components/heraa-cell/index.vue";
import tips from "@/utils/tips";
import {mapState} from "vuex";
import {uploadForm} from "@/services/liank";
import my_upload_card from "@/components/my_upload_card/index.vue";
import PayCard from "@/components/PayCard/PayCard.vue";
import FileNameCard from "@/components/FileNameCard/FileNameCard.vue";
import InputRange from "@/components/InputRange/InputRange.vue";
import {createOrder, getTaskId} from "@/services/order";

export default {
  name: 'print_file',
  components: {InputRange, FileNameCard, PayCard, my_upload_card, heraaCell, navBar, my_form_item},
  data() {
    return {
      files: {},
      ext: '', // 扩展名
      nums: 1, // 打印份数
      printType: 0, // 打印什么
      totalPrice: 0, // 该付的价格
      isDoubleSided: false,
      printColor: false,
      radioCurrent: '1', // 打印方向
      radioEdge: '2', // 打印边距
      paperSize: '9', //打印纸类型
      automaticRotation: 1, // 内容自动旋转

      pageRange: [], // 页面数量
      pageSize: 0,
      flag: true,

      showUpload: false, // 上传中
      uploadProgress: 0,
    }
  },

  computed: {
    ...mapState(['store', "machine", "printer", "machineOnline"]),
    lang() {
      console.log(this.$t('print_pay'))
      return this.$t('print_pay')
    },
  },
  onLoad(options) {
    console.log(options)
    const {file, pages, print_type} = options
    const tempFile = JSON.parse(decodeURIComponent(file));
    this.pageSize = parseInt(pages);
    this.files = tempFile;
    console.log("pages:", tempFile);
    this.ext = getFileExtension(tempFile.name)
    this.pageRange = [1, this.pageSize]

    // 哪儿来的
    if (print_type) {
      this.printType = print_type;
    }

    this.calculatePrice();
  },

  methods: {
    getCanPaper,
    //预览 打开 看见  (微信小程序打开时一直报错)
    onRadioEdgeChange(e) {
      this.radioEdge = e.detail.value;
    },

    openPreview() {
      const {name, path} = this.files
      uni.openDocument({
        filePath: path,
        fileType: getFileExtension(name),
        success: () => {
          console.log('打开文档成功');
        }
      })
    },

    // 选择纸
    onPaperType(event) {
      const {value} = event.detail
      this.paperSize = value
      this.radioEdge = value === '8' ? '3' : '2'
      this.calculatePrice();
    },

    // 添加和却掉 打印数量
    onNums(event) {
      this.nums = event.value
      this.calculatePrice();
    },

    handleRangeChange({leftValue, rightValue}) {
      this.pageRange = [leftValue, rightValue]
      this.calculatePrice()
    },

    // 双面点击事
    onDouble(e) {
      this.isDoubleSided = e.target.value;
      this.calculatePrice();
    },

    // 彩色打印点击
    onPrintColor(e) {
      this.printColor = e.target.value;
      this.calculatePrice();
    },

    // 打印方向 radio Group
    onOrientationRadioGroup(event) {
      const {value} = event.detail
      this.radioCurrent = value
      if (this.paperSize === '9') {
        this.radioEdge = value === '1' ? '2' : '3'
      }
      console.log("this.radioCurrent", this.radioCurrent)
    },

    // 内容自动旋转
    onAutomaticRotation(event) {
      this.automaticRotation = event.detail.value
    },

    // 计算价格
    // calculatePrice() {
    //   // a4_black_white_price: "0.50"
    //   // a4_color_price: "1.00"
    //   // a4_double_black_white_price: "1.00"
    //   // a4_double_color_price: "1.50"
    //   // a4_double_image_black_white_price: "1.20"
    //   // a4_double_image_color_price: "1.50"
    //
    //
    //   const nums = this.nums; // 打印份数
    //   const pageRange = this.pageRange; // 页码范围，比如 [1, 10]
    //   const printColor = this.printColor; // 是否彩色
    //   const double = this.isDoubleSided; // 是否双面
    //   const paperSize = parseFloat(this.paperSize) // 打印纸 类型
    //
    //   // 确保字符串价格转为数值
    //   const a4_black_white_price = parseFloat(this.printer.a4_black_white_price);
    //   const a4_color_price = parseFloat(this.printer.a4_color_price);
    //   const a4_double_black_white_price = parseFloat(this.printer.a4_double_black_white_price);
    //   const a4_double_color_price = parseFloat(this.printer.a4_double_color_price);
    //
    //   total_page = (pageRange[1] - (pageRange[0] - 1))
    //   console.log(total_page)
    //   if (double) {
    //     total_page = total_page % 2 ? total_page + 1 : total_page
    //     console.log(total_page)
    //   }
    //   const page_num = total_page * nums
    //   console.log(nums)
    //   console.log(total_page)
    //
    //   if (paperSize === 8) {  // A3
    //     const a3_black_white_price = parseFloat(this.printer.a3_black_white_price);
    //     const a3_color_price = parseFloat(this.printer.a3_color_price);
    //     const a3_double_black_white_price = parseFloat(this.printer.a3_double_black_white_price);
    //     const a3_double_color_price = parseFloat(this.printer.a3_double_color_price);
    //     console.log('A3=======')
    //     if (printColor && double) {
    //       this.totalPrice = (page_num / 2) * a3_double_color_price;
    //     } else if (!printColor && double) {
    //       this.totalPrice = (page_num / 2) * a3_double_black_white_price;
    //     } else if (printColor && !double) {
    //       this.totalPrice = page_num * a3_color_price;
    //     } else if (!printColor && !double) {
    //       this.totalPrice = page_num * a3_black_white_price;
    //     }
    //   } else { // a4
    //     // 根据选择和单双面计算价格
    //     if (printColor && double) {
    //       this.totalPrice = (page_num / 2) * a4_double_color_price;
    //     } else if (!printColor && double) {
    //       this.totalPrice = (page_num / 2) * a4_double_black_white_price;
    //     } else if (printColor && !double) {
    //       this.totalPrice = page_num * a4_color_price;
    //     } else if (!printColor && !double) {
    //       this.totalPrice = page_num * a4_black_white_price;
    //     }
    //   }
    //
    //   console.log("totalPrice: " + this.totalPrice);
    // },

    // 计算价格
    calculatePrice() {
      // 获取所需的参数
      const {nums, pageRange, printColor, isDoubleSided: double, paperSize, printer} = this;

      let totalPages = 0;
      // 计算总页数
      totalPages = pageRange[1] - (pageRange[0] - 1);
      // if (double) {
      //   // 双面打印时如果是奇数页,需要加1页
      //   totalPages = totalPages % 2 ? totalPages + 1 : totalPages;
      // }
      // 计算实际打印页数(份数 * 页数)
      const pageNum = totalPages * nums;

      // 获取不同纸张类型的价格配置
      const getPrices = (size) => {
        console.log("size -=-=", size)
        const prefix = size.toLowerCase();
        console.log("prefix -=-=", prefix)
        return {
          single: { // 单面价格
            black: parseFloat(printer[`${prefix}_black_white_price`]),
            color: parseFloat(printer[`${prefix}_color_price`])
          },
          double: { // 双面价格
            black: parseFloat(printer[`${prefix}_double_black_white_price`]),
            color: parseFloat(printer[`${prefix}_double_color_price`])
          }
        };
      };

      // 根据纸张类型(A3/A4)获取对应价格
      const prices = getPrices(parseInt(paperSize) === 8 ? 'a3' : 'a4');

      // 根据打印配置计算最终价格
      const price = prices[double ? 'double' : 'single'][printColor ? 'color' : 'black'];
      console.log("double ? (pageNum / 2) * price", (pageNum / 2) * price)
      this.totalPrice = double ? (pageNum / 2) * price : pageNum * price;
    },


    // 获取当前打印的参数
    getPrintParams(isPreview) {
      const {printer: {port, driver_name}, machine: {device_id, device_password}} = this;
      const {
        files: {url, name}, printColor, isDoubleSided, nums, pageRange,
        radioCurrent, radioEdge, paperSize, automaticRotation, ext, pageSize
      } = this;
      return {
        deviceId: device_id,
        deviceKey: device_password,
        devicePort: port, // 打印机端口
        printerModel: driver_name, // 打印机型号
        dmCopies: nums, // 打印份数
        dmPaperSize: parseInt(paperSize),
        isPreview, // 预览
        dmDefaultSource: 7,
        pdfKernel: 'mode1', // 文字增强
        // pdfRev: 0,// 文档逆序功能 (用户选择)
        jpAutoRotate: automaticRotation, // 内容自动旋转
        reportDeviceStatus: 1, // 拦截设备状态异常任务
        reportPrinterStatus: 1, // 拦截打印机状态异常任务
        jpAutoAlign: 'z5', // 自动对齐
        jpAutoScale: 4, // 自动缩放
        jpScale: 'fit', // 缩放
        jobFile: url, // 上传文件 url
        dmColor: printColor ? 2 : 1,
        name, // 打印文件名
        ext, // 打印文件扩展名
        page: pageRange[1] - pageRange[0] + 1, // 打印页数
        dmOrientation: parseInt(radioCurrent), // 打印纸张方向
        dmDuplex: isDoubleSided ? parseInt(radioEdge) : 1, // 双面打印
        jpPageRange: `${pageRange[0]}-${pageRange[1]}`, // 文档页数范围
      };
    },

    // 点击 预览
    async onFilePreview() {
      uni.showLoading({title: '加载中....'})
      const printParams = this.getPrintParams(1);

      try {
        const uploadFileData = await uploadForm(printParams);
        console.log("uploadFileData -=-=-=", uploadFileData);
        const {data: {task_id}, msg, code} = uploadFileData;
        if (code === 200) {
          printParams.taskId = task_id
          console.log("printFileFun-=--=-=-=- task_id", printParams)
          await uni.navigateTo({
            url: `/pages/print_loading/print_loading?params=${
                encodeURIComponent(JSON.stringify({type: 0, print_params: printParams}))}`
          });
        }
      } catch (error) {
        tips.toast(error.msg);
      } finally {
        uni.hideLoading();
      }
    },

    // 付款
    async printPay() {
      if (!this.machineOnline) {
        tips.toast(this.otherLang.not_printer);
        this.$store.commit("setMachineOnline");
        return;
      }
      const printParams = this.getPrintParams(0);

      console.log("params -=-=-=-==", printParams)

      uni.showLoading({title: '加载中...'});
      const createOrderResult = await createOrder({
        printer_id: this.printer.id, params: printParams, type: 'file', files: [printParams.jobFile]
      });
      const {code, data, msg} = createOrderResult
      console.log("createOrderResult -=-=-=-== ", createOrderResult)

      if (code === 200) {
        const {wechat_order, order_id} = data;
        uni.requestPayment({
          ...wechat_order,
          success: async (res) => {
            console.log("uni.requestPayment", res)
            tips.toast('支付成功');
            const tackIdRes = await getTaskId(order_id);
            const {code, data: {task_id}, msg} = tackIdRes;
            if (code === 200) {
              console.log("printFileFun-=--=-=-=- task_id", order_id, task_id)
              printParams.taskId = task_id
              await uni.navigateTo({
                url: `/pages/print_loading/print_loading?params=${
                    encodeURIComponent(JSON.stringify({order_id, type: 0, print_params: printParams}))}`
              });
            } else {
              tips.toast(msg, 3000);
              console.log("printFileFun-=--=-=-=-", tackIdRes)
            }
          },
          fail: (err) => {
            console.log('fail:', err);
          },
          complete(result) {
            uni.hideLoading();
            console.log("uni.requestPayment -==-=-=", result)
          }
        });
      } else {
        console.log(msg)
        uni.hideLoading();
        tips.toast(msg);
      }
    },
  },
}
</script>

<style>

</style>
